from typing import Dict, Optional
import json
import os

class AIConfig:
    """AI模型配置管理类"""
    def __init__(self, api_key: str = "", model_name: str = "gpt-3.5-turbo"):
        self.config_file = 'ai_config.json'
        self.default_config = {
            'model': model_name,
            'api_key': api_key,
            'temperature': 0.7,
            'max_tokens': 1000,
            'timeout': 30
        }
        
        if not api_key:
            raise ValueError("API密钥不能为空")
            
        self.current_config = self.load_config()
        
        # 使用构造函数参数更新配置
        if api_key:
            self.set_config('api_key', api_key)
        if model_name:
            self.set_config('model', model_name)
    
    @property
    def api_key(self) -> str:
        return self.get_config('api_key')
    
    @property
    def model_name(self) -> str:
        return self.get_config('model')

    def load_config(self) -> Dict:
        """加载配置文件，如果不存在则创建默认配置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            return self.default_config.copy()
        except Exception as e:
            print(f'加载配置文件失败: {e}')
            return self.default_config.copy()
    
    def save_config(self) -> bool:
        """保存当前配置到文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.current_config, f, indent=4, ensure_ascii=False)
            return True
        except Exception as e:
            print(f'保存配置文件失败: {e}')
            return False
    
    def get_config(self, key: str) -> Optional[str]:
        """获取指定配置项"""
        return self.current_config.get(key)
    
    def set_config(self, key: str, value: str) -> bool:
        """设置指定配置项"""
        if key in self.default_config:
            self.current_config[key] = value
            return self.save_config()
        return False
    
    def reset_config(self) -> bool:
        """重置为默认配置"""
        self.current_config = self.default_config.copy()
        return self.save_config()